package com.ly.controller;

import com.alipay.api.internal.util.AlipaySignature;
import com.github.pagehelper.PageInfo;
import com.ly.bean.*;
import com.ly.service.*;
import com.ly.util.*;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileWriter;
import java.util.*;

/**
 * @author 李岩
 * @date 2021/12/17-15:43           user_car 购物车的cookie
 *                                  uuid  用户的
 * @describe
 */
@Controller
@RequestMapping("/shop/")
public class ShopController {
    private final Logger logger= LoggerFactory.getLogger(ShopController.class);
    private ShopController(){
        System.out.println("ShopController   的controller层");
    }
    @Reference(url = "dubbo://localhost:20851")
    private ProductService productService;
    @Reference(url = "dubbo://localhost:20851")
    private ProductCategoryService productCategoryService;
    @Reference(url = "dubbo://localhost:20851")
    private ProductImagesService productImagesService;
    @Reference(url = "dubbo://localhost:20851")
    private ProductCommentsService productCommentsService;
    @Reference(url = "dubbo://localhost:20882")
    private UserService userService;
    @Reference(url = "dubbo://localhost:20887")
    private SeckillGoodsService seckillGoodsService;
    @Reference(url = "dubbo://localhost:20887")
    private SeckillOrderService seckillOrderService;
    @Reference(url = "dubbo://localhost:20888")
    private ProductSolrService solrService;
    @Autowired
    private FreeMarkerConfig freeMarkerConfig;

    //展示首页
    @RequestMapping("showIndex")
    public String showIndex(Model model, @CookieValue(required = false) String uuid){
        //一级商品分类
        List<EasybuyProductCategory> firstList=null;
        //一级商品分类下面的二级商品分类
        HashMap<Integer, List<EasybuyProductCategory>> secondMap = new HashMap<>();
        //二级商品分类下面的三级商品分类
        HashMap<Integer, List<EasybuyProductCategory>> thirdMap = new HashMap<>();
        //一级商品分类下面的所有三级商品分类
        HashMap<Integer, List<EasybuyProductCategory>> thirdAllCatetoryMap = new HashMap<>();
        //一级商品分类下面的前六件商品
        HashMap<Integer, List<EasybuyProduct>> firstProductMap = new HashMap<>();
        try {
            if (uuid!=null && !"".equals(uuid)){
                EasybuyUser loginUser = userService.findUserByRedis(uuid);
                model.addAttribute("loginUser",loginUser);
            }

            logger.info("进入展示首页");
            //一级商品下面的分类
            firstList = productCategoryService.findCategoryByPid(0);
            for (EasybuyProductCategory firstCategory : firstList) {
                //一级商品分类下面的所有三级商品分类
                List<EasybuyProductCategory> firstAllCatetoryList = productCategoryService.findThirdCategoryByPid(firstCategory.getId());
                thirdAllCatetoryMap.put(firstCategory.getId(),firstAllCatetoryList);

                //一级商品分类下面的二级商品分类
                List<EasybuyProductCategory> secondList = productCategoryService.findCategoryByPid(firstCategory.getId());
                secondMap.put(firstCategory.getId(),secondList);
                //一级商品分类下面的前六件商品
                List<EasybuyProduct> firstProductList = productService.selectSixByCategoryLevel1Id(firstCategory.getId());
                firstProductMap.put(firstCategory.getId(),firstProductList);
                for (EasybuyProductCategory secondCategory : secondList) {
                    //二级商品分类下面的三级商品分类
                    List<EasybuyProductCategory> thirdList = productCategoryService.findCategoryByPid(secondCategory.getId());
                    thirdMap.put(secondCategory.getId(),thirdList);
                }
            }

            //查询首页显示的秒杀商品
            List<EasybuySeckillGoods> killGoodsList = seckillGoodsService.showSixKillProduct();

            model.addAttribute("firstList",firstList);
            model.addAttribute("secondMap",secondMap);
            model.addAttribute("thirdMap",thirdMap);
            model.addAttribute("thirdAllCatetoryMap",thirdAllCatetoryMap);
            model.addAttribute("firstProductMap",firstProductMap);

            model.addAttribute("killGoodsList",killGoodsList);

            return "index";
        } catch (Exception e) {
            logger.error("进入展示首页异常  "+e);
        }
        return "redirect:/error.html";
    }
    //商品详情
    @RequestMapping("product")
    public String showProduct(Integer productId,String pageNum,@CookieValue(required = false) String uuid){
        System.out.println("productId  "+productId+";pageNum=  "+pageNum);
        //一级商品分类
        List<EasybuyProductCategory> firstList=null;
        //一级商品分类下面的二级商品分类
        HashMap<Integer, List<EasybuyProductCategory>> secondMap = new HashMap<>();
        //二级商品分类下面的三级商品分类
        HashMap<Integer, List<EasybuyProductCategory>> thirdMap = new HashMap<>();
        //一级商品分类下面的所有三级商品分类
        HashMap<Integer, List<EasybuyProductCategory>> thirdAllCatetoryMap = new HashMap<>();
        //一级商品分类下面的前六件商品
        HashMap<Integer, List<EasybuyProduct>> firstProductMap = new HashMap<>();
        try {
           if (new File("/ProductDetail_"+productId+".html").exists()){
               return "redirect:/product/ProductDetail_"+productId+".html";
           }

            logger.info("进入商品详情页");
            //一级商品下面的分类
            firstList = productCategoryService.findCategoryByPid(0);
            for (EasybuyProductCategory firstCategory : firstList) {
                //一级商品分类下面的所有三级商品分类
                List<EasybuyProductCategory> firstAllCatetoryList = productCategoryService.findThirdCategoryByPid(firstCategory.getId());
                thirdAllCatetoryMap.put(firstCategory.getId(),firstAllCatetoryList);

                //一级商品分类下面的二级商品分类
                List<EasybuyProductCategory> secondList = productCategoryService.findCategoryByPid(firstCategory.getId());
                secondMap.put(firstCategory.getId(),secondList);
                //一级商品分类下面的前六件商品
                List<EasybuyProduct> firstProductList = productService.selectSixByCategoryLevel1Id(firstCategory.getId());
                firstProductMap.put(firstCategory.getId(),firstProductList);
                for (EasybuyProductCategory secondCategory : secondList) {
                    //二级商品分类下面的三级商品分类
                    List<EasybuyProductCategory> thirdList = productCategoryService.findCategoryByPid(secondCategory.getId());
                    thirdMap.put(secondCategory.getId(),thirdList);
                }
            }

            //根据商品id展示商品信息
            EasybuyProduct product = productService.selectProductByPrimaryKey(productId);
            //根据商品id查询商品的附属图片数据
            List<EasybuyProductImages> productImagesList = productImagesService.selectProductImagesByPid(productId);
            //根据商品id查询该商品的评论信息
            PageInfo<EasybuyProductComment> commentPageInfo = productCommentsService.selectProductCommentsKey(productId,pageNum);
            //根据商品id统计该商品的评论占比
            Map<String, Object> commentMap = productCommentsService.selectLevelCommentNUmBypid(productId);
            //该件商品的总评论数
            Integer zts = Integer.parseInt(commentMap.get("zts").toString());
            //好评的个数
            Integer hps = Integer.parseInt(commentMap.get("hps").toString());
            //中评的个数
            Integer zps = Integer.parseInt(commentMap.get("zps").toString());
            //差评的个数
            Integer cps = Integer.parseInt(commentMap.get("cps").toString());
            //计算百分比
            int hpsbfb=(int)((hps*1.0/zts)*100);
            int zpsbfb=(int)((zps*1.0/zts)*100);
            int cpsbfb=(int)((cps*1.0/zts)*100);
            Map<String, Object> resuMap = new HashMap<>();


            resuMap.put("product",product);
            resuMap.put("productImagesList",productImagesList);
            resuMap.put("commentList",commentPageInfo.getList());
            resuMap.put("pages",commentPageInfo.getPages());
            resuMap.put("hpsbfb",hpsbfb);
            resuMap.put("zpsbfb",zpsbfb);
            resuMap.put("cpsbfb",cpsbfb);
            //System.out.println("hpsbfb="+hpsbfb+";zpsbfb="+zpsbfb+";cpsbfb="+cpsbfb);
            System.out.println("secondMap="+secondMap);
            System.out.println("thirdMap="+thirdMap);
            resuMap.put("firstList",firstList);
            resuMap.put("secondMap",secondMap);
            resuMap.put("thirdMap",thirdMap);
            resuMap.put("thirdAllCatetoryMap",thirdAllCatetoryMap);
            resuMap.put("firstProductMap",firstProductMap);

            //生成该页面
            Configuration configuration = freeMarkerConfig.getConfiguration();
            Template template = configuration.getTemplate("ProductDetail.ftl");
            FileWriter writer = new FileWriter(new File("D:\\Idea\\workspace\\dubbo_springboot\\easybuy_springboot_dubbo\\easybuy_shop_web\\src\\main\\resources\\static\\product\\ProductDetail_" + productId + ".html"));
            template.process(resuMap,writer);
            writer.flush();
            writer.close();

            return "redirect:/product/ProductDetail_"+productId+".html";
        } catch (Exception e) {
            logger.error("进入展示首页异常  "+e);
        }
        return "redirect:/error.html";
    }

    //添加购物车
    @RequestMapping("addUserCar")
    public String addUserCar( Integer pid, Integer buyNum, @CookieValue(required = false) String uuid, HttpServletRequest request, HttpServletResponse response){
        System.out.println("pid="+pid+";"+buyNum);
        try {
            System.out.println("11111111111111111");
            //要添加到购物车的商品信息
            EasybuyProduct easybuyProduct = productService.selectProductByPrimaryKey(pid);
            //添加购物车的时候先判断用户是否登录
            //已登录直接把购物车redis
            EasybuyUser loginUser = userService.findUserByRedis(uuid);
            if (loginUser!=null){
                productService.addProductCarToRedis(easybuyProduct,loginUser,buyNum);
                return "redirect:showCar";
            }
            List<CarItem> userCarList=null;
            //未登录放到cookie   首先判断cookie中是否存在购物车
            //获取当前cookie的购物车信息
            String userCarStr = CookieUtil.getCookieValue(request, "user_car", true);
            System.out.println("userCarStr ="+userCarStr);
            System.out.println("-----------------------");
            //不存在即为第一次添加商品  那就创建购物车对象放进去
            if (userCarStr==null || "".equals(userCarStr)){
                userCarList=new ArrayList<>();
            }else {// 存在直接添加数值即可
                userCarList= JsonUtil.jsonToList(userCarStr,CarItem.class);
            }
            //判断此次购买的商品是否在购物车存在
            boolean isHave=false;//默认商品第一次购买
            for (CarItem carItem : userCarList) {
                if (carItem.getEasybuyProduct()==null){
                    continue;
                }
                if (easybuyProduct.getId().equals(carItem.getEasybuyProduct().getId())){
                    // 存在直接添加数值即可
                    isHave=true;
                    carItem.setBuyNum(carItem.getBuyNum()+buyNum);
                    break;
                }
            }
            //判断商品不在购物车中
            if (isHave==false){
                CarItem carItem = new CarItem();
                carItem.setEasybuyProduct(easybuyProduct);
                carItem.setBuyNum(buyNum);
                System.out.println("carItem1  ="+carItem);
                userCarList.add(carItem);
            }
            // 创建购物车放到 cookie中
            userCarStr = JsonUtil.objectToJson(userCarList);
            logger.info("目前购物车的数据:  "+userCarStr);
            CookieUtil.setCookie(request,response,"user_car",userCarStr,true);
            return "redirect:showCar";
        } catch (Exception e) {
            logger.info("添加购物车出现异常   "+e);
        }

        return "error";
    }

    //展示购物车
    @RequestMapping("showCar")
    public String showCar(HttpServletRequest request,HttpServletResponse response){
        logger.info("展示购物车 ");
        try {

            //获取用户登录信息
            String uuid = CookieUtil.getCookieValue(request, "uuid");
            EasybuyUser loginUser = userService.findUserByRedis(uuid);
            //从cooki中获取购物车信息
            String carItemStr = CookieUtil.getCookieValue(request, "user_car",true);
            System.out.println("carItemStr   "+carItemStr);
            List<CarItem> carItemList = null;
            if (carItemStr==null || "".equals(carItemStr)){
                carItemList=new ArrayList<>();
            }else {
                carItemList= JsonUtil.jsonToList(carItemStr,CarItem.class);
            }
            //如果是未登录  直接从cooki中获取 购物车信息 返回
            if (loginUser==null){
                request.setAttribute("carItemList",carItemList);
                return "BuyCar";
            }
            //如果已登录状态  那么cookie和redis中都存在 购物车  先把cookie中的信息同步到redis中再从redis中获取
            for (CarItem carItem : carItemList) {
                productService.addProductCarToRedis(carItem.getEasybuyProduct(),loginUser,carItem.getBuyNum());
            }
            //cookie同步到redis后需要删除cookie中的信息
            CookieUtil.deleteCookie(request,response,"user_car");
            //从redis中获取该用户所有的购物车信息
            carItemList = productService.findProductCarItemFromRedis(loginUser);
            request.setAttribute("carItemList",carItemList);
            request.setAttribute("loginUser",loginUser);
            logger.info("从redis中获取购物车信息:   "+carItemList);
            return "BuyCar";
        } catch (Exception e) {
           logger.error("展示购物车异常   "+e);
        }
        return "error";
    }
    //修改购物车里面的购买数值
    @RequestMapping("addBuyNum")
    @ResponseBody
    public Result addBuyNum(Integer buyNum,Integer pid,HttpServletRequest request,HttpServletResponse response){
        logger.info("修改购物车里面的购买数值  pid="+pid+";buyNum"+buyNum);
        //获取用户登录信息
        String uuid = CookieUtil.getCookieValue(request, "uuid");
        try {
            EasybuyUser loginUser = userService.findUserByRedis(uuid);
            //如果用户未登录  那就直接修改cookie中的值
            if (loginUser==null){
                //从cooki中获取购物车信息
                String carItemStr = CookieUtil.getCookieValue(request, "user_car",true);
                System.out.println("carItemStr   "+carItemStr);
                List<CarItem> carItemList = null;
                if (carItemStr==null || "".equals(carItemStr)){
                    carItemList=new ArrayList<>();
                }else {
                    carItemList= JsonUtil.jsonToList(carItemStr,CarItem.class);
                }
                CarItem carItem1 = new CarItem();
                //遍历cookie中的购物车信息  如果商品id一致 ，那就修改购买商品的数量
                for (CarItem carItem : carItemList) {
                    if (carItem.getEasybuyProduct().getId().equals(pid)){
                        carItem.setBuyNum(buyNum);
                        carItem1=carItem;
                        break;
                    }
                }
                carItemStr=JsonUtil.objectToJson(carItemList);
                logger.info("修改购物车的数据之后:  "+carItemStr);
                CookieUtil.setCookie(request,response,"user_car",carItemStr,true);
                return Result.getResult(true,200,"修改成功",carItem1.getEasybuyProduct() );
            }
            //如果用户已登录  就需要修改redis中的值
            EasybuyProduct product = productService.selectProductByPrimaryKey(pid);
            System.out.println("要修改购物车的商品  "+product);
            //把修改好的数据传到redis中
            productService.addProductCarToRedis(product,loginUser,buyNum);
            logger.info("修改购物车的数据成功");
            return Result.getResult(true,200,"修改成功",product);
        } catch (Exception e) {
            logger.error("修改购物车里面的购买数值出现异常   "+e);
        }
        return Result.getResult(false,404,"修改失败",null );
    }
    //删除购物车里面的内容
    @RequestMapping("deleteCarItem")
    @ResponseBody
    public Result deleteCarItem(Integer pid,HttpServletRequest request,HttpServletResponse response){
        System.out.println("pid   "+pid);
        //获取用户登录信息
        String uuid = CookieUtil.getCookieValue(request, "uuid");
        try {
            EasybuyUser loginUser = userService.findUserByRedis(uuid);
            //如果用户未登录  那就直接删除cookie中的商品
            if (loginUser==null){
                //从cooki中获取购物车信息
                String carItemStr = CookieUtil.getCookieValue(request, "user_car",true);
                List<CarItem> carItemList = null;
                if (carItemStr==null || "".equals(carItemStr)){
                    carItemList=new ArrayList<>();
                }else {
                    carItemList= JsonUtil.jsonToList(carItemStr,CarItem.class);
                }
                //遍历cookie中的购物车信息  如果商品id一致 ，那就修改购买商品的数量
                for (CarItem carItem : carItemList) {
                    if (carItem.getEasybuyProduct().getId().equals(pid)){
                        carItemList.remove(carItem);
                        break;
                    }
                }
                carItemStr=JsonUtil.objectToJson(carItemList);
                logger.info("删除购物车的数据之后:  "+carItemStr);
                CookieUtil.setCookie(request,response,"user_car",carItemStr,true);
                return Result.getResult(true,200,"删除成功",null);
            }
            //如果用户已登录  就需要删除cookie中的商品
            EasybuyProduct product = productService.selectProductByPrimaryKey(pid);
            System.out.println("要删除购物车的商品  "+product);
            //把要删除的数据传到redis中
            productService.deleteProductCarItemFromRedis(loginUser,product.getId());
            logger.info("删除购物车的数据成功");
            return Result.getResult(true,200,"删除成功",null);
        } catch (Exception e) {
            logger.error("修改购物车里面的购买数值出现异常   "+e);
        }
        return Result.getResult(false,404,"删除失败",null );
    }
    //显示BuyCat_two界面
    @RequestMapping("showBuyCarTwo")
    public String showBuyCarTwo(HttpServletRequest request,HttpServletResponse response){
        //获取用户登录信息
        String uuid = CookieUtil.getCookieValue(request, "uuid");
        try {
            EasybuyUser loginUser = userService.findUserByRedis(uuid);
            logger.info("显示BuyCat_two界面  "+loginUser);
            if (loginUser==null){
                return "login";
            }
            //为添加订单做准备工作  1.显示所有数据
            List<CarItem> carItemList = productService.findProductCarItemFromRedis(loginUser);
            //DecimalFormat format = new DecimalFormat("0.00");
            double totalMoney=0.00;
            for (CarItem carItem : carItemList) {
                totalMoney+=(carItem.getBuyNum()* carItem.getEasybuyProduct().getPrice());
            }
            //2.根据用户id 获取该用户的收货地址表的信息
            List<EasybuyUserAddress> addressList = userService.selectUserAdressByUid(loginUser.getId());
            UserVip userVip = new UserVip();
            userVip.setUserId(loginUser.getId());
            userVip.setMonth(DateUtil.getNowDateYm());
            //3.判断用户是否是vip
            int userVipByuid = userService.findUserVipByuid(userVip);
            request.setAttribute("carItemList",carItemList);
            request.setAttribute("addressList",addressList);
            request.setAttribute("userVipByuid",userVipByuid);
            request.setAttribute("loginUser",loginUser);
            request.setAttribute("totalMoney",totalMoney);
            return "BuyCar_Two";
        } catch (Exception e) {
            logger.error("显示BuyCat_two界面出现异常   "+e);
        }
        return "error";
    }

    //抢购商品详情
    @RequestMapping("detail")
    public String detail(@RequestParam Integer id, Model model){

        try {
            logger.info("抢购商品详情 "+id);
            //抢购商品详情
            EasybuySeckillGoods seckillGood = seckillGoodsService.selectKillGoodFromRedis(id);
            System.out.println(seckillGood);
            //计算剩余时间
            Date date = new Date();
            //获取当前时间到截止时间的剩余秒数
            long sysconds=(seckillGood.getEndTime().getTime()-date.getTime())/1000;
            //(seckillGood.price-seckillGood.costPrice)/seckillGood.price
            double zk=1.00-((seckillGood.getPrice()-seckillGood.getCostPrice())/seckillGood.getPrice());

            model.addAttribute("seckillGood",seckillGood);
            model.addAttribute("sysconds",sysconds);
            model.addAttribute("zk",zk);
            return "SellDetails";
        } catch (Exception e) {
            logger.error("抢购商品详情 出现异常"+e);
        }
        return "error";
    }
    //添加抢购商品的订单信息
    @RequestMapping("addKillOder")
    public String addKillOder(@RequestParam Integer seckillId,@CookieValue(required = false) String uuid ){
        try {
            logger.info("添加抢购商品的订单信息 seckillId="+seckillId);
            EasybuyUser loginUser =(EasybuyUser) userService.findUserByRedis(uuid);
            if (loginUser==null){
                return "login";
            }
            System.out.println("00000");
            String killOderId = seckillOrderService.addKillOder(loginUser.getId() + "", seckillId);

            return "redirect:findKillOrder";
            //return "";
        } catch (Exception e) {
            logger.error("添加抢购商品的订单信息 出现异常"+e);
        }
        return "error";
    }
    //获取该用户的未支付秒杀订单列表信息
    @RequestMapping("findKillOrder")
    public String findKillOrder(@CookieValue(required = false) String uuid,Model model){
        try {
            logger.info("获取该用户的未支付秒杀订单列表信息");
            EasybuyUser loginUser =(EasybuyUser) userService.findUserByRedis(uuid);
            if (loginUser==null){
                return "login";
            }
            //获取的是订单  订单中还没有数据 所以前台显示不全
            List<EasybuySeckillOrder> seckillOrderList = seckillOrderService.findKillOrderFromRedisByUid(loginUser.getId());
            System.out.println("size= "+seckillOrderList.size());
            //获取最早的抢购订单信息 并计算剩余支付时间
            Date minOrderDate = new Date();
            Long killOrderId=null;
            String goodsId=null;
            for (EasybuySeckillOrder seckillOrder : seckillOrderList) {
                System.out.println("seckillOrder= "+seckillOrder);
                if (seckillOrder.getCreateTime().getTime()<minOrderDate.getTime()){
                    minOrderDate=seckillOrder.getCreateTime();
                    goodsId=seckillOrder.getSeckillId().toString();
                }
            }
            //并计算剩余的支付时间(5分钟的支付时间)
            long syzfss=(60-(new Date().getTime()-minOrderDate.getTime())/1000);

            //根据用户id 获取该用户的收货地址表的信息
            List<EasybuyUserAddress> addressList = userService.selectUserAdressByUid(loginUser.getId());
            model.addAttribute("seckillOrderList",seckillOrderList);
            model.addAttribute("syzfss",syzfss);
            model.addAttribute("goodsId",goodsId);
            model.addAttribute("loginUser",loginUser);
            model.addAttribute("addressList",addressList);
            return "KillOrder";
        } catch (Exception e) {
            logger.error("获取该用户的未支付秒杀订单列表信息 出现异常 "+e);
        }
        return "error";
    }
    //跳转到去支付页面
    @RequestMapping("zhifu")
    public void zhifu(@RequestParam Integer killId,EasybuySeckillOrder seckillOrder,HttpServletResponse response,@CookieValue(required = false) String uuid){
        try {
            logger.info("跳转到去支付页面 支付的抢购订单信息为  "+seckillOrder);
            EasybuyUser loginUser = (EasybuyUser) userService.findUserByRedis(uuid);
            if (loginUser!=null){

                EasybuySeckillOrder killOrder = seckillOrderService.findKillOrderFromRedisBySeckillId(killId, loginUser.getId());
                System.out.println("killOrder "+killOrder);
                //设置支付完毕后的返回路径
                AlipayConfig.return_url="http://localhost:8092/shop/return_url_kill";
                ALiPayUtil.getALiPay(response,killOrder.getId(),killOrder.getMoney(),seckillOrder.getReceiver(),seckillOrder.getReceiverAddress(),AlipayConfig.return_url);
                //补全订单信息
                killOrder.setReceiver(seckillOrder.getReceiver());
                killOrder.setReceiverAddress(seckillOrder.getReceiverAddress());
                killOrder.setReceiverMobile(seckillOrder.getReceiverMobile());
                killOrder.setPayTime(new Date());
                killOrder.setStatus("1");//0 代表生成订单但是还没有补全支付信息  1代表补全信息 未付款 2 支付完成
                //进入支付页面  然后把这个抢购的商品订单从redis中删除 然后再添加到MySQL中
                seckillOrderService.addKillOrderToMysql(killOrder,loginUser.getId());
            }
        } catch (Exception e) {
            logger.error("跳转到去支付页面 异常 "+e);
        }
    }
    //
    @RequestMapping("return_url_kill")
    public String return_url(HttpServletRequest request) {
        try {

            //获取支付宝GET过来反馈信息
            Map<String,String> params = new HashMap<String,String>();
            Map<String,String[]> requestParams = request.getParameterMap();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                //乱码解决，这段代码在出现乱码时使用
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
                params.put(name, valueStr);
            }

            boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名

            //——请在这里编写您的程序（以下代码仅作参考）——
            if(signVerified) {
                //商户订单号
                String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

                //支付宝交易号
                String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

                //付款金额
                String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");

                EasybuySeckillOrder seckillOrder = new EasybuySeckillOrder();
                seckillOrder.setId(Integer.valueOf(out_trade_no));
                seckillOrder.setStatus("2");
                seckillOrder.setTransactionId(trade_no);
                System.out.println("支付成功后 seckillOrder="+seckillOrder);
                //修改数据库中订单的状态
                seckillOrderService.updateByPrimaryKeySelective(seckillOrder);
                return "redirect:findKillOrder";
            }else {
                //out.println("trade_no:"+trade_no+"<br/>out_trade_no:"+out_trade_no+"<br/>total_amount:"+total_amount);
                System.out.println("验签失败");
                //out.println("验签失败");
            }
            //——请在这里编写您的程序（以上代码仅作参考）——

        } catch (Exception e) {
            logger.error("验签出现异常   "+e);
        }
        return "error";
    }
    //抢购商品的剩余支付时间为0 删除此订单
    @RequestMapping("deleteKillOrder")
    public String deleteKillOrder(Integer goodId,@CookieValue(required = false) String uuid){
        try {
            logger.info("抢购商品的剩余支付时间为0 删除此订单 "+goodId);
            EasybuyUser loginUser =(EasybuyUser) userService.findUserByRedis(uuid);
            seckillOrderService.deleteKillOrderFromRedis(goodId,loginUser.getId());
            //删除完毕后调转到订单页面
            return "redirect:findKillOrder";
        } catch (Exception e) {
            logger.error("抢购商品的剩余支付时间为0 删除此订单 出现异常 "+e);
        }
        return "error";
    }

    //使用solr实现多条件分页查询
    @RequestMapping("search")
    public String search(Integer pageNum,EasybuyProduct product,Model model){

        try {
            HashMap<String, Object> map = new HashMap<>();

            logger.info("使用solr实现多条件分页查询 "+pageNum+";  product="+product);
            if (pageNum==null){
                pageNum=1;
            }

            //获取一级分类列表
            List<EasybuyProductCategory> categoryList = productCategoryService.findCategoryByPid(0);

            map.put("product",product);
            map.put("pageSize",4);
            map.put("pageIndex",(pageNum-1)*4);

            Map<String, Object> resuMap=null;
            if (product.getKeyword()!=null && !"".equals(product.getKeyword())){
                resuMap= solrService.findLightHighProductByMap(map);
            }else {
                resuMap= solrService.findProductByMap(map);
            }

            model.addAttribute("pageNum",pageNum);
            model.addAttribute("categoryList",categoryList);
            model.addAttribute("resuMap",resuMap);
            model.addAttribute("product",product);

            return "ProductList";
        } catch (Exception e) {
            logger.error("使用solr实现多条件分页查询 出现异常"+e);
        }
        return "error";
    }
}
